//  https://zhuanlan.zhihu.com/p/428691576
export default {
  getArr(n = 1, val = 0) {
    return Array(n).fill(val);
  },
  digitize(n) {
    // 将数字转为整数数组 digitize(123) -> [1, 2, 3]
    return [...`${n}`].map(i => parseInt(i));
  },
  intersection(a, b) {
    // 数组交集
    const s = new Set(b);
    return a.filter(x => s.has(x));
  },
  uniArr(arr = {}) {
    // 数组去重
    return Array.from(new Set(arr));
  },
  getUnique(array, condition) {
    // JSON 数组去重  condition 迭代条件 eg: (a, b) => a.t === b.t
    return array.filter(
      (item, index, self) =>
        index === self.findIndex(existItem => condition(existItem, item))
    );
  },
  uniArrByKey(arr, key) {
    // JSON数组去重
    let map = {};
    return arr.filter(e => !map[e[key]] && (map[e[key]] = 1));
  },
  arrByKey(arr = [], key) {
    // JSON数组键值序列
    return arr.map(e => {
      return e[key] == 0 ? 0 : isNaN(e[key] || NaN) ? "-" : e[key];
    });
  },
  arrRange(arr) {
    // 数组最小值最大值
    return [Math.min(...arr), Math.max(...arr)];
  },
  arrScrambling(arr) {
    // 乱序数组
    for (let i = 0; i < arr.length; i++) {
      const index = Math.round(Math.random() * (arr.length - 1 - i)) + i;
      [arr[i], arr[index]] = [arr[index], arr[i]];
    }
    return arr;
  },
  randomFromArr(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
  },
  pick(obj, arr) {
    // 提取键值  pick({ a: 1, b: '2', c: 3 }, ['a', 'c']);
    return arr.reduce(
      (acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc),
      {}
    );
  },
  findLabelInTree(tree, keyArr) {
    // 在tree中 查询key对应的label
    var list = [];
    function inner(val, obj) {
      obj.map(e => {
        list.push({
          value: val + e.value,
          label: e.label
        });
        if (e.children) inner(val + e.value, e.children);
      });
    }
    inner("", tree);
    var cur = list.filter(e => e.value == keyArr.join(""))[0];
    return cur ? cur.label : "";
  },
  productFilter(all, query) {
    // 下拉过滤 依赖  pinyinUtil
    // github项目地址：https://github.com/liuxianan/pinyinjs
    // 支持 编码 产品名汉字-全拼-首字母

    return !query
      ? all.slice(0, 100)
      : all.filter(item => {
          var str = query.toString().trim().toLowerCase();
          var each = (item.name + item.code).toLowerCase();
          if (each.includes(str)) {
            return true;
          } else {
            var chinese = pinyinUtil.default.getPinyin(each, " ", false);
            return (
              chinese.replaceAll(" ", "").includes(str) ||
              chinese.split(" ").map(e => e.substr(0, 1)).join("").includes(str)
            );
          }
        });
  }
};
